package netty5.demo1;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by GanJc on 2015/11/19.
 */
public class TimeClientHandler extends ChannelInboundHandlerAdapter {

    private static final Logger logger = LoggerFactory.getLogger(TimeClientHandler.class);

    private  int count = 0;
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info("链路创建成功!");
        byte[] req = ("Time"+System.getProperty("line.separator")).getBytes();
        for (int i = 0; i < 100; i++) {
            ByteBuf byteBuf = Unpooled.buffer(req.length);
            byteBuf.writeBytes(req);
            ctx.writeAndFlush(byteBuf);
            ctx.flush();
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        String resp  = (String) msg;
        logger.info("现在时间是:{} 现在count：{}",resp,++count);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.info("异常信息:{}", cause.getMessage());
        ctx.close();
    }

}
